import _ from 'lodash';
import {useCallback, useMemo, useState} from 'react';
import {Table, Button, Space, Radio} from 'acud';
import {initData, getColumns} from './options';

const EditableTable = () => {
    const [data, setData] = useState(initData);
    const [edit, setEdit] = useState(true);

    const handleChange = useCallback(
        (value: string, index: number, name: string) => {
            const newData: any = data[index];
            newData[name] = value;
            setData(data);
        },
        [data, setData]
    );

    const columns = useMemo(() => {
        return getColumns({
            edit,
            handleChange,
        });
    }, [edit, handleChange]);

    const handleAdd = () => {
        const newData = Array.from(data);
        newData.push({
            resolution: '',
            level: 0,
            description: '',
            key: _.uniqueId(),
        });
        setData(newData);
    };

    const handleClick = () => {
        console.log('---data->', data);
    };

    return (
        <>
            <Space style={{marginBottom: 20}}>
                <Radio.Group defaultValue={0} onChange={(v: any) => setEdit(!v?.target?.value)}>
                    <Radio value={0}>分辨率</Radio>
                    <Radio value={1}>ScaleDenominator</Radio>
                </Radio.Group>
            </Space>
            <Table
                bordered
                rowClassName="editable-row" 
                rowKey="key"
                dataSource={data || []}
                columns={columns}
            />
            <Space>
                <Button onClick={handleAdd}>添加层级</Button>
                <Button type="primary" onClick={handleClick}>
                    提交
                </Button>
            </Space>
        </>
    );
};

export default EditableTable;
